package com.lwm.springcloud.controller;


import com.lwm.springcloud.entity.MsgInfo;
import com.lwm.springcloud.entity.Payment;
import com.lwm.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lwmzzz
 * @version 1.0
 * @date 2020/11/23 21:49
 * @description
 */
@RestController
@RequestMapping("/payment/")
@Slf4j
public class PaymentController {
    @Resource
    PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Resource
    DiscoveryClient discoveryClient;

    @PostMapping("/c")
    public MsgInfo create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("========插入结果为：{}", result);
        if (result > 0) {
            return new MsgInfo<>(200, "插入数据库成功 " + serverPort, result);
        } else {
            return new MsgInfo<>(444, "插入数据库失败 " + serverPort, null);
        }
    }

    @GetMapping("/r/{id}")
    public MsgInfo<Payment> getPayment(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentNew(id);
        log.info("=== ==查询结果为：{}", payment);
        if (ObjectUtils.isEmpty(payment)) {
            return new MsgInfo<>(444, "查询失败 " + serverPort, null);
        } else {
            return new MsgInfo<>(200, "查询成功 " + serverPort, payment);
        }
    }

    @GetMapping("/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("======service: {}", service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/lb")
    public String getPaymentLB() {
        return serverPort;
    }
}
